package com.imooc.order.converter;

import java.util.ArrayList;
import java.util.List;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.imooc.order.dataobject.OrderDetail;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.ResultEnum;
import com.imooc.order.exception.OrderException;
import com.imooc.order.form.OrderForm;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class OrderForm2OrderDTO {

	public static OrderDTO convert(OrderForm form) {
		OrderDTO dto = new OrderDTO();
		dto.setBuyerAddress(form.getAddress());
		dto.setBuyerName(form.getName());
		dto.setBuyerOpenid(form.getOpenid());
		dto.setBuyerPhone(form.getPhone());
		
		List<OrderDetail> orderDetailList = new ArrayList<>();
		
		Gson g = new Gson();
		
		try {
			orderDetailList = g.fromJson(form.getItems(), new TypeToken<List<OrderDetail>>() {
			}.getType());
		} catch (Exception e) {
			log.error("参数错误,{}",form.getItems());
			throw new OrderException(ResultEnum.PARAM_ERROR);
		}
		dto.setOrderDetailList(orderDetailList);
		
		return dto;
	}
}
